package cn.redragon.soa.config;

import cn.redragon.soa.amqp.handler.RedisKeyExpirationListener;
import java.text.MessageFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

@Configuration
public class RedisListenerConfig {

    private static String KEY_EVENT_WORD = "__keyevent@{0}__:expired";

    @Value("${spring.redis.expire-database}")
    private Integer expireDb;

    @Autowired
    private RedisKeyExpirationListener keyExpirationListener;

    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory,
                                                                       MessageListenerAdapter messageListenerAdapter) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //下面这种方式是灵活配置，针对每个库的失效key做处理
        container.addMessageListener(messageListenerAdapter, new PatternTopic(MessageFormat.format(KEY_EVENT_WORD, expireDb)));
        return container;
    }

    @Bean
    public MessageListenerAdapter messageListenerAdapter() {
        return new MessageListenerAdapter(keyExpirationListener);
    }
}
